//
//  BWMapWindowController.m
//  Earthinizer
//
//  Created by markd on 6/6/09.
//  Copyright Borkware 2009 . All rights reserved.
//

#import "BWMapWindowController.h"


@implementation BWMapWindowController
@synthesize mapView = mapView_;

- (void)windowDidLoad {
    NSURL *mapURL =
        [NSURL URLWithString:@"http://borkware.com/earthinizer/map.html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:mapURL];

    [[self.mapView mainFrame] loadRequest:request];
    [[[self.mapView mainFrame] frameView] setAllowsScrolling:NO];

    [self.mapView setNeedsDisplay:YES];

} // windowDidLoad


- (NSString *)colorAsString:(NSColor *)color {

    CGFloat red, green, blue, alpha;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];

    NSString *colorRep = [NSString stringWithFormat:@"%02x%02x%02x%",
                                   (int)(red * 255),
                                   (int)(green * 255),
                                   (int)(blue * 255)];
    return colorRep;
                                   
} // colorAsString


- (void)showRoute:(NSString *)routeString
        withColor:(NSColor *)color {
    NSMutableString *code = [NSMutableString string];
    [code appendString:@"map.clearOverlays();\n"];
    [code appendString:@"var polyline = new GPolyline([\n"];

    NSArray *coordStrings = [routeString componentsSeparatedByString:@" "];

    double maxLng, minLng, maxLat, minLat;
    maxLng = maxLat = -5000;
    minLng = minLat = 5000;
    
    for (NSString *coord in coordStrings) {
        NSArray *coords = [coord componentsSeparatedByString:@","];
        
        if (coords.count < 2) continue;
        NSString *latString = [coords objectAtIndex:1];
        NSString *lngString = [coords objectAtIndex:0];
        double lat = [latString doubleValue];
        double lng = [lngString doubleValue];
        if (lat == 0.0 || lng == 0.0) continue;
        if (lat < minLat) minLat = lat;
        if (lat > maxLat) maxLat = lat;
        if (lng < minLng) minLng = lng;
        if (lng > maxLng) maxLng = lng;
        [code appendFormat:@"  new GLatLng(%f, %f),\n", lat, lng];
    }

    NSString *colorString = [self colorAsString:color];
    [code appendFormat:@"], \"#%@\", 10);\n", colorString];
    [code appendString:@"map.addOverlay(polyline);\n"];

    double centerLat = minLat + ((maxLat - minLat) / 2.0);
    double centerLng = minLng + ((maxLng - minLng) / 2.0);
    [code appendFormat:@"map.setCenter(new GLatLng(%f, %f), 13);\n",
          centerLat, centerLng];

    [[self.mapView windowScriptObject] evaluateWebScript:code];
    
} // showRoute


@end // BWMapWindowController

